package com.ruoyi.web.wx.controller;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.conversation.mapper.ConversationMapper;
import com.ruoyi.distributionrule.domain.DistributionRule;
import com.ruoyi.distributionrule.mapper.DistributionRuleMapper;
import com.ruoyi.finance.domain.Finance;
import com.ruoyi.finance.mapper.FinanceMapper;
import com.ruoyi.order.domain.Order;
import com.ruoyi.order.domain.vo.OrderVO;
import com.ruoyi.order.service.IOrderService;
import com.ruoyi.user.domain.User;
import com.ruoyi.user.domain.vo.UserVO;
import com.ruoyi.user.mapper.UserMapper;
import com.ruoyi.user.service.IUserService;
import com.ruoyi.web.websocket.WebSocketServer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

@Api(tags = "关闭订单")
@RestController
@RequestMapping("/wx/websocket")
public class WebSocketController {

    private final WebSocketServer webSocketServer;

    public WebSocketController(WebSocketServer webSocketServer) {
        this.webSocketServer = webSocketServer;
    }

    @Autowired
    private IOrderService orderService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private FinanceMapper financeMapper;
    @Autowired
    private DistributionRuleMapper distributionRuleMapper;
    @Autowired
    private ConversationMapper conversationMapper;

    /**
     * 关闭两个用户的所有 WebSocket 连接
     */
    @ApiOperation("关闭两个用户所有 WebSocket 连接")
    @PostMapping("/closeUsers")
    @Transactional
    public AjaxResult closeUsers(@RequestParam("orderId") String orderId, @RequestParam("isSession") Integer isSession) {
        try {
            String reason = "订单会话已结束，无法建立连接";
            OrderVO orderVO1 = orderService.selectOrderByOrderId(orderId);
            if (isSession == 0) {
                webSocketServer.closeSessionByOrderAndUser(orderId, orderVO1.getUserId(), reason);
                webSocketServer.closeSessionByOrderAndUser(orderId, orderVO1.getExpertId(), reason);
            }
            Order order = new Order();
            order.setOrderId(orderId);
            order.setIsSession(1);
            order.setOrderStatus("0");
            order.setIsEvaluate("1");
            order.setCompleteTime(DateUtils.getNowDate());
            orderService.updateOrder(order);
            User user = userMapper.selectUserByUserId(orderVO1.getExpertId());
            OrderVO orderVO = orderService.selectOrderByOrderId(orderId);
            BeanUtils.copyProperties(orderVO, order);
            BigDecimal freezeAmount = user.getFreezeAmount();
            DistributionRule distributionRule = new DistributionRule();
            distributionRule = distributionRuleMapper.selectDistributionRuleList(distributionRule).get(0);
            // 专家接单提成  接单提成百分比
            String orderCommission = distributionRule.getOrderCommission();
            // 转换成 BigDecimal 并除以 100，变成 0.1
            BigDecimal commissionRate = new BigDecimal(orderCommission).divide(BigDecimal.valueOf(100));
            BigDecimal actualPayment = order.getActualPayment();
            BigDecimal orderMultiply = actualPayment.multiply(commissionRate);
            // 专家可提现金额
            freezeAmount = freezeAmount.subtract(orderMultiply);
            user.setWithdrawableAmount(user.getWithdrawableAmount().add(orderMultiply));
            user.setFreezeAmount(freezeAmount);
            userMapper.updateUser(user);
            // 推荐专家提成
            String expertCommission = distributionRule.getExpertCommission();
            BigDecimal expertCommissionRate = new BigDecimal(expertCommission).divide(BigDecimal.valueOf(100));
            String inviterId = user.getInviterId();
            if (inviterId != null) {
                User user1 = userMapper.selectUserByUserId(inviterId);
                if (user1 != null) {
                    BigDecimal freezeAmount1 = user1.getFreezeAmount();
                    BigDecimal actualPayment1 = order.getActualPayment();
                    BigDecimal multiply = actualPayment1.multiply(expertCommissionRate);
                    BigDecimal subtract = freezeAmount1.subtract(multiply);
                    user1.setWithdrawableAmount(user1.getWithdrawableAmount().add(multiply));
                    user1.setFreezeAmount(subtract);
                    userMapper.updateUser(user1);
                }
            }
            // 用户提成
            String userCommission = distributionRule.getUserCommission();
            BigDecimal userCommissionRate = new BigDecimal(userCommission).divide(BigDecimal.valueOf(100));
            User user2 = userMapper.selectUserByUserId(orderVO1.getUserId());
            String inviterId1 = user2.getInviterId();
            if (inviterId1 != null) {
                User user3 = userMapper.selectUserByUserId(inviterId1);
                if (user3 != null) {
                    if (user3.getIsExpert() == 0) {
                        BigDecimal freezeAmount1 = user3.getFreezeAmount();
                        BigDecimal actualPayment1 = order.getActualPayment();
                        BigDecimal multiply = actualPayment1.multiply(userCommissionRate);
                        BigDecimal subtract = freezeAmount1.subtract(multiply);
                        user3.setWithdrawableAmount(user3.getWithdrawableAmount().add(multiply));
                        user3.setFreezeAmount(subtract);
                        userMapper.updateUser(user3);
                    }
                }
            }
            Finance finance = new Finance();
            finance.setOrderId(orderId);
            List<Finance> finances = financeMapper.selectFinanceList(finance);
            if (!finances.isEmpty()) {
                Finance finance1 = finances.get(0);
                finance1.setSettlementTime(DateUtils.getNowDate());
                financeMapper.updateFinance(finance1);
            }
            return AjaxResult.success("已关闭用户 " + orderVO1.getUserId() + " 和 " + orderVO1.getExpertId() + " 的所有连接");
        } catch (Exception e) {
            return AjaxResult.error("关闭连接失败: " + e.getMessage());
        }
    }
}